package com.dream.prm.socket;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.sun.javafx.collections.MappingChange.Map;

/**
 * @author w.g
 * @date 2019-07-13
 * 
 */
@SuppressWarnings("all")
@Component
public class MyWebSocketHandler implements WebSocketHandler {
	
	public static final HashMap<String, WebSocketSession> socketSessionMap;
	 
	static {
		socketSessionMap = new HashMap<String, WebSocketSession>();
	}

	//建立连接后处理
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String jspCode=(String)session.getAttributes().get("jspCode");
		if(socketSessionMap.get(jspCode)==null) {
			socketSessionMap.put(jspCode, session);
		}
//		for(int i=0;i<10;i++) {
//			session.sendMessage(new TextMessage("{\"number\":\""+i+"\"}") );
//		}
	}

	//接收消息，并发送出去
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		// TODO Auto-generated method stub
		session.sendMessage(message);
	}

	//抛出异常时处理
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		// TODO Auto-generated method stub
		if(session.isOpen()) {
			session.close();
		}
		Iterator<Entry<String, WebSocketSession>> it = socketSessionMap.entrySet().iterator();
		//移除socket会话
		while(it.hasNext()) {
			Entry<String, WebSocketSession> entry=it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				socketSessionMap.remove(entry.getKey());
				System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
				break;
			}

		}
		
	}

	//连接关闭后处理
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Websocket:" + session.getId() + "已经关闭");
		Iterator<Entry<String, WebSocketSession>> it = socketSessionMap
				.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				socketSessionMap.remove(entry.getKey());
				System.out.println("Socket会话已经移除,用户ID: " + entry.getKey());
				break;
			}
		}
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}
	/**
	 * TODO 群发信息
	 * @param msg
	 */
	public void broadcast(final TextMessage msg) {
		Iterator<Entry<String, WebSocketSession>> it=socketSessionMap.entrySet().iterator();
		
		while(it.hasNext()) {
			final Entry<String, WebSocketSession> entry=it.next();
			if(entry.getValue().isOpen()) {
				new Thread(()->{
					try {
						if(entry.getValue().isOpen()) {
							entry.getValue().sendMessage(msg);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}).start(); 
			}
		}
	}
	
	/**
	 * TODO 发送消息到浏览器页面
	 * @param msg
	 * @param type
	 */
	public void sendMessageToJsp(TextMessage msg,String type) {
		Iterator<Entry<String, WebSocketSession>> it=socketSessionMap.entrySet().iterator();
		
		while(it.hasNext()) {
			final Entry<String, WebSocketSession> entry=it.next();
			if(entry.getValue().isOpen()&&entry.getKey().contains(type)) {
				new Thread(()->{
					try {
						if(entry.getValue().isOpen()) {
							entry.getValue().sendMessage(msg);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}).start(); 
			}
		}
	}

}
